<script>
  import ClickEdit from '@/components/clickEdit/index.vue';
  import signInput from "@/components/am-sign-input/am-sign-input.vue"
  import { onSiteResultColumn } from '@/utils/column'
  import { getMedicalDict, getDictDataNotesList, foodProductionAdd, foodProductionUpdate } from '@/api/order';
  import config from '@/config';
  import EnterpriseSelector from "@/components/dialog/enterprise-selector.vue"
  import ProblemTable from './problemTable.vue';
  import SignList from '@/components/signatureList/index.vue'

  uni.setNavigationBarTitle({
    title: '食品、食品添加剂生产许可现场核查报告'
  })
  export default {
    props: {
      workOrderDetail: Object,
      editStatus: String,
      categoryDetail: Object
    },
    components: {
      ClickEdit,
      signInput,
      EnterpriseSelector,
      ProblemTable,
      SignList
    },
    data(){
      return {
        form: {},
        onSiteResultColumn,
        checkGroupPositionList: [],
        checkOpiniionList: [],
        checkConclusionList: [],
        killCheckList: [],
        workOrderSignatureList: [
          { signaturePosition: '核查组组长', signature: ''},
          { signaturePosition: '组员', signature: ''},
          { signaturePosition: '观察员', signature: ''},
        ],
        approverPersonSignList: [
          { signaturePosition: '申请人签名（盖章）：', signature: ''},
        ],
        centerPersonSignList: [
          { signaturePosition: '申请人签名（盖章）：', signature: ''},
        ],
        workOrderSignatureHuiYiList: [
          { signaturePosition: '核查组组长', signature: ''},
          { signaturePosition: '组员', signature: ''},
          { signaturePosition: '观察员', signature: ''},
        ],

        current: 1,
        uploadUrl: config.uploadUrl,
        scoreList: [],
        selectOpen: false,
        selectOrderList: [],
        foodCategoryList: [],
      }
    },
    computed: {
      // 格式化数据
      formatterShow(){
        return (data, key) => {
          let str = '[修改]'
          if(key == 'categoryDetails'){
            return data[key].split(',').map(item => this.foodCategoryList.find(child => child.value == item)?.label || '').join(',') + str
          }else if(key == 'checkResult'){
            return (this.checkOpiniionList.find(child => child.value == data[key])?.label || '')  + str
          }else{
            return (this.foodCategoryList.find(child => child.value == data[key])?.label || '')  + str
          }
        } 
      }
    },
    watch: {
      workOrderDetail(val){
        if(!val.id) return;
        this.form.workOrderId = val.id;
      },
      categoryDetail(val){
        if(!val.id) return;
        console.log(val, 'date')
        this.$set(this, 'form', val);
        this.workOrderSignatureList = val.workOrderSignatureList
        this.approverPersonSignList = [
          { signaturePosition: '申请人签名（盖章）：', signature: val.approverPersonSign},
        ]
        this.centerPersonSignList = [
          { signaturePosition: '申请人签名（盖章）：', signature: val.centerPersonSign},
        ]
        this.workOrderSignatureHuiYiList = val.workOrderSignatureHuiYiList;
        this.selectOrderList = val.checkResultList;
        this.$set(this.form, 'checkTime', [val.checkStartTime, val.checkEndTime])
      },
      'form.deliveryReceiptTime': {
        handler(val){
          console.log(val, 'date')
        }, 
        deep: true
      }
    },
    created(){
      this.getDictData();
      this.getFoodCategory();
    },
    methods: {
      getDictData(){
        getMedicalDict('checkGroup_position').then(res => {
          this.checkGroupPositionList = res.data
        });
        getMedicalDict('check_opiniion').then(res => {
          this.checkOpiniionList = res.data
        });
        getMedicalDict('check_conclusion').then(res => {
          this.checkConclusionList = res.data
        });
        getMedicalDict('kill_check').then(res => {
          this.killCheckList = res.data
        });
      },
      handleSignListUpdate(updatedList, type) {
        console.log(updatedList,222)
        if(type == 1){
          this.workOrderSignatureList = updatedList
        }
			},

      // 打开选择器
			openSelector(i) {
				this.$refs.selector.open();
        this.editIndex = i
			},
      handleConfirmEdit(value, key, index){
        if(key == 'standardLabel'){ 
          let data = {...this.selectOrderList[index]};
          data[key] = value
          this.$set(this.selectOrderList, index, data)
        }else if(key == 'checkTime'){
          this.$set(this.form, key, value)
          this.$set(this.form, 'checkStartTime', value[0])
          this.$set(this.form, 'checkEndTime', value[1])
        }else {
          this.$set(this.form, key, value)
        }
      },
      // 请求食品类别
      getFoodCategory (code = '0000', index = 0) {
        if(index == 3) return;
        getDictDataNotesList(code).then(res => {
          let obj = {};
          obj[code] = res.data;
          this.foodCategoryList.push(...res.data);
          res.data.forEach(item => {
            return this.getFoodCategory(item.value, index + 1)
          })
        })
      },
      changeValue(value, key){
        console.log(value, 'sign')
        this.$set(this, key, value)
      },
      changeTime(value, key){
        this.$set(this.form, key, value)
      },
      handleConfirm(e){
        if(this.editIndex != null){
          this.$set(this.selectOrderList, this.editIndex, {...e, adjWorkOrderId: e.id });
        }else {
          this.selectOrderList.push({...e, adjWorkOrderId: e.id });
        }
        this.editIndex = null
        console.log(this.selectOrderList, e,1111)
      },
      handleClose(){

      },

      // 提交
      async submitForm(type){
        try{
          if(type == '1' && this.current == 1) {
            this.$refs.problemTable.getList();
            return this.current += 1;
          }
          let data = { ...this.form };
          let key = ['foodCategory', 'categoryName', 'categoryDetails', 'checkResult', 'standardLabel', 'adjWorkOrderId']
          let params = {
            ...data,
            auditStatus: type,
            centerPersonSign: this.centerPersonSignList[0].signature,
            workOrderSignatureHuiYiList: this.workOrderSignatureHuiYiList.map(item => ({ ...item, signType: 1 })),
            workOrderSignatureList: this.workOrderSignatureList.map(item => ({ ...item, signType: 0 })),
            approverPersonSign: this.approverPersonSignList[0].signature,
            checkResultList: this.selectOrderList.map(item => {
              let obj = {};
              key.forEach(k => obj[k] = item[k])
              return {
                ...obj,
              }
            }),
            workOrderId: this.workOrderDetail.id
          }
          console.log(params);
          delete params.checkTime
          let res;
          if(this.form.id){
            res = await foodProductionUpdate(params)
          }else {
            res = await foodProductionAdd(params);
          }
          
          if (res.code !== 0) {
            throw new Error(res.msg || '服务器处理异常');
          }
          // 统一处理成功逻辑
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });

          // 导航控制（根据模式跳转不同层级）
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1500);
        }catch(err){
          console.log(err)
        }
        
      }
    }
  }
</script>

<template>
  <view>
    <view class="page flex-col flex gap-4" v-show="current == 1">
      <uni-card :is-shadow="false">
        <view class="flex flex-col gap-4">
          <view>
            <text>根据《食品生产许可管理办法》《食品生产许可审查通则》《</text>
            <view class="inline-block">
              <ClickEdit :value="form.guidelines" @confirm="e => handleConfirmEdit(e, 'guidelines')">
                <view class="border-b px-10">{{ form.guidelines || '点击编辑' }}</view>
              </ClickEdit>
            </view>
            <text>》核查组于</text>
            <view class="inline-block">
              <ClickEdit :value="form.checkTime" formType="date-range" @confirm="e => handleConfirmEdit(e, 'checkTime')"> 
                <view class="inline-block">
                  <text class="border-b px-10">{{ form.checkStartTime || '编辑年编辑月编辑日' }}</text>
                  <text>至</text>
                  <text class="border-b px-10">{{ form.checkEndTime || '编辑年编辑月编辑日' }}</text>
                </view>
                
              </ClickEdit>
            </view>
            <text>对<text class="border-b px-10">{{ workOrderDetail.operatorName }}</text>进行了现场核查，结果如下：</text>
          </view>
          <view class="font-bold font-20 text-center">一、现场核查结论</view>
          <view>（一）现场核查正常开展，经综合评价，本次现场核查的结论是：</view>
          <view>
            <text class="btn" @click="openSelector(null)">选择工单</text>
          </view>
          <uni-table>
            <uni-tr>
              <uni-th align="center" v-for="item in onSiteResultColumn" :key="item.key">{{ item.title }}</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in selectOrderList" :key="item.id">
              <uni-td align="center" v-for="child in onSiteResultColumn" :key="child.key">
                <view @click="openSelector(index)">
                  <text v-if="child.key == 'index'">{{ index + 1 }}[修改]</text>
                  <ClickEdit v-else-if="child.key == 'standardLabel'" :value="selectOrderList[index][child.key]" @confirm="e => handleConfirmEdit(e, child.key, index)">
                    {{ item[child.key] || '点击编辑' }}
                  </ClickEdit>
                  <text v-else-if="child.key !== 'checkResult' && child.key != 'index'">
                    {{ formatterShow(item, child.key) }}
                  </text>
                  <text v-else>
                    {{ formatterShow(item, child.key) }}
                  </text>
                </view>
                
              </uni-td>
            </uni-tr>
          </uni-table>
          <view>（二）因申请人的下列原因导致现场核查无法正常开展，本次现场核查的结论判定为未通过现场核查：</view>
          <view class="dashed-box2 uni-list">
            <radio-group @change="e => changeTime(e.detail.value, 'failSceneCheck')" class="flex flex-col gap-4">
              <label class="flex item-center gap-4" v-for="(item, index) in checkConclusionList" :key="item.label">
                <view>
                  <radio :value="item.value" :checked="form.failSceneCheck === item.value" />
                </view>
                <view>
                  <text>{{item.label}}</text>
                  <view class="inline-block" v-if="item.value == '4'">
                    <ClickEdit :value="form.subjectiveReason" @confirm="e => handleConfirmEdit(e, 'subjectiveReason')">
                      <text class="px-4 border-b">{{ form.subjectiveReason || '点击编辑'}}</text>
                    </ClickEdit>
                  </view>
                </view>
              </label>
            </radio-group>
          </view>
          <view>（三）因下列原因导致现场核查无法正常开展，中止现场核查：</view>
          <view class="dashed-box2 uni-list">
            <radio-group @change="e => changeTime(e.detail.value, 'terSceneCheck')" class="flex flex-col gap-4">
              <label class="flex item-center gap-4" v-for="(item, index) in killCheckList" :key="item.label">
                <view>
                  <radio :value="item.value" :checked="form.terSceneCheck === item.value" />
                </view>
                <view>
                  <text>{{item.label}}</text>
                  <view class="inline-block" v-if="item.value == '1'">
                    <ClickEdit :value="form.objectiveReasons" @confirm="e => handleConfirmEdit(e, 'objectiveReasons')">
                      <text class="px-4 border-b">{{ form.objectiveReasons || '点击编辑'}}</text>
                    </ClickEdit>
                  </view>
                </view>
              </label>
            </radio-group>
          </view>
          
        </view>
      </uni-card>
      <uni-card :is-shadow="false">
        <view class="flex flex-col gap-4">
          <view class="text-center font-bold font-20">核查组成员签字</view>
        </view>
        <view class="dashed-box2">
          <SignList canvasKey="workOrderSignatureList" :signList="workOrderSignatureList" :date="form.deliveryReceiptTime"  @update:signList="data => changeValue(data, 'workOrderSignatureList')" @date-change="e => changeTime(e, 'deliveryReceiptTime')" />
        </view>
        <view class="dashed-box2 uni-list">
          <view class="flex items-center">
            <text >申请人意见：</text>
            <uni-easyinput v-model="form.approverOpinion"></uni-easyinput>
          </view>
          <SignList canvasKey="approverPersonSignList" :showDate="false" :showAdd="false" :signList="approverPersonSignList" />
          
          <view class="title-row2">
            <view class="edit-btn" @click="handleSign(item.type)">
              <evan-checkbox >是否启用电子签章功能</evan-checkbox>

            </view>

          </view>

          <view class="dashed-box3">
            <text style="font-size: 20rpx;font-weight: bold;">+点此签章（部门公章）</text>
          </view>
          <SignList :showSignList="false" :showAdd="false" :date="form.approverPersonDate" @date-change="e => changeTime(e, 'approverPersonDate')" />
        </view>

      </uni-card>
    </view>
    <view v-show="current == 2" class="page flex-col flex gap-4">
      <uni-card :is-shadow="false">
        <view class="flex flex-col gap-4">
          <view class="font-bold font-20 text-center">二、食品、食品添加剂生产许可现场核查得分及存在的问题</view>
          <view class="flex flex-col gap-4">
            <ProblemTable :originList="selectOrderList" ref="problemTable" :foodCategoryList="foodCategoryList" />
          </view>
        </view>
      </uni-card>
      <uni-card :is-shadow="false">
        <view class="flex flex-col gap-4">
          <view class="text-center font-bold font-20">核查组成员签字</view>
        </view>
        <view class="dashed-box2">
          <SignList canvasKey="workOrderSignatureHuiYiList" :signList="workOrderSignatureHuiYiList" :date="form.checkSignDateOne"  @update:signList="data => changeValue(data, 'workOrderSignatureHuiYiList')" @date-change="e => changeTime(e, 'checkSignDateOne')" />
        </view>
        <view class="dashed-box2 uni-list">
          <view class="flex items-center">
            <text >申请人意见：</text>
            <uni-easyinput v-model="form.remark"></uni-easyinput>
          </view>
          <SignList canvasKey="centerPersonSignList" :showDate="false" :showAdd="false" :signList="centerPersonSignList" />
          
          <view class="title-row2">
            <view class="edit-btn" @click="handleSign(item.type)">
              <evan-checkbox >是否启用电子签章功能</evan-checkbox>

            </view>

          </view>

          <view class="dashed-box3">
            <text style="font-size: 20rpx;font-weight: bold;">+点此签章（部门公章）</text>
          </view>
          <SignList :showSignList="false" :showAdd="false" :date="form.centerPersonDate" @date-change="e => changeTime(e, 'centerPersonDate')" />
        </view>

      </uni-card>
    </view>
    <view v-show="editStatus!='FALSE'" style="background: #fff; padding: 10px;">
      <!-- 签章区域 -->
      <button type="primary" style="margin-top: 15px;" @click="submitForm('1')">{{ current == 1 ? '下一步（1/2）' : ''}}</button>
      <button type="primary" style="margin-top: 10px;" @click="submitForm('0')">暂存</button>
      <button type="primary" style="margin-top: 15px;" v-show="current == 2" @click="current--" >返回上一页</button>
    </view>
    <enterprise-selector tableType="2" :query="{orderType: '2', orderCategory: '14', auditStatus: '1'}" type="radio" ref="selector" :multiple="false" @confirm="handleConfirm" @close="handleClose" />
  </view>
  
</template>

<style lang="scss" scoped>
  .page {
    flex: 1;
    background-color: #e9f1fe;
    box-sizing: border-box;
    padding: 10px 0;
  }

  .dashed-box2 {
    width: 100%;
    margin: 24rpx auto;
    padding: 12rpx;
    border: 2rpx dashed #333;
    border-radius: 10rpx;
    background: #fff;
    position: relative;
  }

  .uni-list-cell{
    display: flex;
    // flex-direction: ;
    
  }

  .title-row2 {
			display: flex;
			justify-content: flex-end;
			align-items: flex-end;
			margin-bottom: 10rpx;

			.title {
				font-size: 16rpx;
				color: #333;
				font-weight: 500;

			}

			.edit-btn {

				.btn-text {
					color: #2196F3;
					font-size: 16rpx;
					margin-left: 60px;
					margin-right: 16rpx;
				}


			}
		}

    /* 虚线容器 */
		.dashed-box3 {
			width: 100%;
			border: 2rpx dashed #0055ff;
			border-radius: 10rpx;
			background: #e5ecff;
			height: 120px;
			/* 设置为flex布局 */
			display: flex;
			/* 水平居中 */
			justify-content: center;
			/* 垂直居中 */
			align-items: center;
		}

    .btn{
      background: #2196F3;
      padding: 10px;
      color: #fff;

    }

</style>